package com.hx.test.controller;

import com.hx.test.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.UUID;

/**
 * Created by hyl on 19/4/21.
 * @author 华云龙
 */
@RestController
public class BookController {

    @Autowired
    @Qualifier("secondJdbcTemplate")
    JdbcTemplate secondJdbcTemplate;

    @PostConstruct
    public void init() {
        secondJdbcTemplate.execute("DROP TABLE IF EXISTS book");
        secondJdbcTemplate.execute("CREATE TABLE book (" //
                + "id VARCHAR(50) NOT NULL," //
                + "name VARCHAR(50) NOT NULL," //
                + "isbn VARCHAR(50) NOT NULL," //
                + "createdAt BIGINT NOT NULL," //
                + "updatedAt BIGINT NOT NULL," //
                + "PRIMARY KEY (id))");
        for (int i = 0; i < 25; i++) {
            Book book = new Book();
            book.setName("Java-" + randomString())
                .setIsbn("ISBN-" + randomString().hashCode() % 2019);
            createBook(book);
        }
    }

    @PostMapping("/api/books")
    public Book createBook(@RequestBody Book book) {
        String id = randomString();
        Long now = System.currentTimeMillis();
        secondJdbcTemplate.update("INSERT INTO book (id, name, isbn, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)", // SQL
                id, book.getName(), book.getIsbn(), now, now);
        return getBook(id);
    }

    @GetMapping("/api/books")
    public List<Book> getBooks() {
        return secondJdbcTemplate.query("SELECT * FROM book ORDER BY createdAt",
                new BeanPropertyRowMapper<>(Book.class));
    }

    @GetMapping("/api/books/{id}")
    public Book getBook(@PathVariable("id") String id) {
        return secondJdbcTemplate.queryForObject("SELECT * FROM book WHERE id=?",
                new BeanPropertyRowMapper<>(Book.class), id);
    }

    private String randomString() {
        return UUID.randomUUID().toString();
    }
}
